package br.com.me.ceap;

import org.apache.commons.io.IOUtils;
import org.apache.cxf.common.util.Base64Utility;
import org.apache.cxf.configuration.security.ProxyAuthorizationPolicy;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * User: Pardini
 * Date: 18/05/12
 * Time: 14:29
 * To change this template use File | Settings | File Templates.
 */
public class WebConnectionUtils {
// -------------------------- STATIC METHODS --------------------------

    protected static WebClient createWebClient(BaseMojo baseMojo, String baseAddress) {
        baseMojo.getLog().info("Using URL " + baseAddress);
        WebClient webClient = WebClient.create(baseAddress);
        addBasicAuthentication(webClient, baseMojo);
        setProxyServer(webClient, baseMojo);
        webClient.header("User-agent", "ceap-plugin");
        webClient.type(MediaType.MULTIPART_FORM_DATA_TYPE);
        webClient.accept(MediaType.MULTIPART_FORM_DATA_TYPE);
        return webClient;
    }

    private static void addBasicAuthentication(WebClient webClient, BaseMojo baseMojo) {
        webClient.header("Authorization", getBasicAuthentication( baseMojo.getUsername(), baseMojo.getPassword()));
    }

    protected static String getBasicAuthentication(String username, String password) {
        return "Basic " + Base64Utility.encode(String.format("%s:%s", username, password).getBytes());
    }

    private static void setProxyServer(WebClient webClient, BaseMojo baseMojo) {
        if ((baseMojo.getProxy_server() != null) && (!baseMojo.getProxy_server().isEmpty())) {
            HTTPConduit httpConduit = WebClient.getConfig(webClient).getHttpConduit();
            HTTPClientPolicy policy = httpConduit.getClient();
            policy.setProxyServer(baseMojo.getProxy_server());
            policy.setProxyServerPort(baseMojo.getProxy_port());

            if ((baseMojo.getProxy_username() != null) && (!baseMojo.getProxy_username().isEmpty())) {
                ProxyAuthorizationPolicy authorization = new ProxyAuthorizationPolicy();
                authorization.setUserName(baseMojo.getProxy_username());
                authorization.setPassword(baseMojo.getProxy_password());
                httpConduit.setProxyAuthorization(authorization);
            }
        }
    }

    public static String getResponseBody(Response response) throws IOException {
        return IOUtils.toString((InputStream) response.getEntity());
    }
}
